<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item class="search-wrap-item" label="标题关键字：" prop="projectTitle">
        <el-input min-width="360px" placeholder="请输入标题关键字" v-model="searchFormData.projectTitle" clearable
          @keyup.enter="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="归属人：" prop="userName">
        <el-input min-width="360px" placeholder="请输入归属人" v-model="searchFormData.userName" clearable
          @keyup.enter="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker style="width: 240px" type="daterange" unlink-panels range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间" :value-on-clear="null" v-model="searchFormData.time" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" @change="getAllRequirements" />
      </el-form-item>
    </el-form>

    <!-- [我负责的需求]列表区域 -->
    <div class="card-layout-box" id="cardLayoutBox">
      <div class="card-not-requirement" v-if="allRequirements.length === 0">
        暂无数据
      </div>
      <!-- 分类 -->
      <div v-if="allRequirements.length !== 0" class="card-box" v-for="(list, index) in allRequirements" :key="index">
        <div class="card-header-box">
          <el-tag :style="{ backgroundColor: fatherStatus(list.status)?.bgColor }">{{ fatherStatus(list.status).text
          }}</el-tag> - {{ list.total }}
        </div>
        <!-- 需求列表 -->
        <div class="card-list-box" :id="`card-list-box-${list.status}`" @scroll="handleScroll(list.status)">
          <ul class="card-list">
            <li class="card-list-item" v-for="item in list.requirements" :key="item.ID"
              :class="{ 'red-bj': item.isOutTime === '是' }">
              <div class="card-list-left">
                <!-- 延期图标 -->
                <div class="icon-img" v-if="item.isOutTime === '是'">
                  <img src="../../../assets/images/icon-delay.png" style="width: 50px;" />
                </div>
                <!-- 需求类别 -->
                <div class="card-list-type">
                  <span>
                    <el-icon :style="{ color: taskTypeContent(item.taskType).color }" :size="14">
                      <Flag />
                    </el-icon>
                    {{ taskTypeContent(item.taskType).text }}
                  </span>
                  <!-- <span>
                    <el-icon :style="{ color: isTsContent(item.isTs).color }" :size="15">
                      <Flag />
                    </el-icon>
                    {{ isTsContent(item.isTs).text }}
                  </span> -->
                </div>
                <!-- 需求标题 -->
                <div class="card-header-title-box" @click="handleRowClick(item.ID)"
                  :class="{ 'card-finished': item.requirementFatherStatus === 9 }">
                  <b>{{ item.requirementName }}</b>
                </div>

                <!-- 附加信息：样式二 -->
                <div class="w-[100%] text-[12px] flex flex-col pl-[5px] pr-[5px]" style="color: #999;">
                  <!-- 审核人、技术负责人、测试负责人 -->
                  <div class="w-[100%] flex flex-row">
                    <!-- <p class="mr-5 w-7/32 truncate" v-if="item.requirementCreateName">创建人：{{ item.requirementCreateName
                      }}</p> -->
                    <p class="mr-[5px] w-[33%] truncate" v-if="item.requirementAuditName">审核人：{{
                      item.requirementAuditName }}
                    </p>
                    <p class="mr-[5px] w-[33%] truncate" v-if="item.requirementBossName">技术负责人：{{
                      item.requirementBossName }}
                    </p>
                    <p class=" w-[33%] truncate" v-if="item.contactTestBossName">测试负责人：{{ item.contactTestBossName }}
                    </p>
                  </div>

                  <!-- 参与研发、运维、测试 -->
                  <div class="w-[100%] flex flex-row" v-if="item.requirementFatherStatus !== 1">
                    <p class="mr-[5px] w-[33%] truncate"
                      v-if="(item.requirementRelevances == '' && item.requirementLinuxs == '')">
                      <span class="text-[red]">未分配研发/运维</span>
                    </p>
                    <p class="mr-[5px] w-[33%] truncate" v-if="item.requirementRelevances || item.requirementLinuxs">
                      研发：{{
                        item.requirementRelevances ? handleStringNames(item.requirementRelevances) : '无' }}</p>
                    <p class="mr-[5px] w-[33%] truncate" v-if="item.requirementRelevances || item.requirementLinuxs">{{
                      item.requirementLinuxs ? `${"运维：" + handleStringNames(item.requirementLinuxs)}` : "运维：无" }}</p>
                    <p class="w-[33%] truncate" v-if="item.isGetTest == 2 && item.contactTestNames !== ''">测试：{{
                      handleStringNames(item.contactTestNames) }}</p>
                    <p class="w-[33%] truncate" v-if="item.isGetTest == 1">
                      <span class="text-[red]">不需要测试参与</span>
                    </p>
                    <p class="w-[33%] truncate"
                      v-if="(item.isGetTest == 2 && item.contactTestNames == '') || item.isGetTest == 3">
                      <span class="text-[red]">未分配测试</span>
                    </p>
                  </div>
                </div>

                <!-- 时间、上线状态、评论状态 -->
                <div class="w-[100%] flex flex-row flex-nowrap items-center pl-[5px] pr-[5px]">
                  <div class="card-list-small-item begin-time">
                    <!-- 任务时间 -->
                    <el-icon>
                      <Clock style="position: absolute;left: 0;top:2px;" />
                    </el-icon>
                    <span>{{ timeToData(item.createAt) }}</span>
                    <span v-if="item.onlineTime"> - </span>
                    <span :class="{ 'red-text': item.isOutTime === '是' }">{{ timeToData(item.onlineTime) }}</span>
                  </div>
                  <div class="w-[60%] flex flex-row flex-nowrap justify-end truncate"
                    v-if="item.requirementFatherStatus == 8">
                    <div>
                      <span
                        :style="{ color: item.requirementOnlineStatus == 1 ? '#515a6e' : item.requirementOnlineStatus == 3 ? 'red' : 'green' }">{{
                          item.requirementOnlineStatus == 1 ? '待确认上线状态' : item.requirementOnlineStatus == 2 ? '上线成功' :
                            '上线失败' }}</span>
                    </div>
                    <div>
                      <span v-if="userAuthId == '555'"
                        :style="{ color: item.tipDevOnlineStatus == 1 ? 'red' : 'green' }">/{{ item.tipDevOnlineStatus
                          == 1 ? '未评论' : '已评论' }}</span>
                      <span v-if="userAuthId == '111'"
                        :style="{ color: item.tipTsOnlineStatus == 1 ? 'red' : 'green' }">/{{ item.tipTsOnlineStatus ==
                          1 ? '未评论' : '已评论' }}</span>
                      <span v-if="userAuthId !== '555' && userAuthId !== '111'"
                        :style="{ color: item.tipDevOnlineStatus == 1 ? 'red' : 'green' }">/{{ item.tipDevOnlineStatus
                          == 1 ? '研发未评论' : '研发已评论' }}</span>
                      <span v-if="userAuthId !== '555' && userAuthId !== '111'"
                        :style="{ color: item.tipTsOnlineStatus == 1 ? 'red' : 'green' }">/{{ item.tipTsOnlineStatus ==
                          1 ? '测试未评论' : '测试已评论' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </li>
            <!-- 懒加载状态指示器 -->
            <li v-if="statusLoadingStates[list.status]" class="loading-indicator">
              <div class="loading-content">
                <el-icon class="is-loading">
                  <Loading />
                </el-icon>
                <span>加载中...</span>
              </div>
            </li>
            <li v-else-if="!statusHasMoreStates[list.status] && list.requirements.length > 0" class="no-more-data">
              <div class="no-more-content">
                没有更多数据了
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <!-- 需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px" :close-on-click-modal="false" v-model="dialogInfoVisible"
      @close="handleCloseDialog" @closed="handleCloseDialog" top="8vh">
      <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData" :isComment="true">
      </CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { ElForm } from "element-plus";
import { Loading } from "@element-plus/icons-vue";
import { handleStringNames } from "@/utils/utils";
import {
  fatherStatus,
  taskTypeContent, timeToData,
} from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";
import {
  postAllInitRequirement,
} from "@/api/newDemands/index";

let useCommonStore = useCommonDataStore();
const loading = ref(false);
const userAuthId = ref<any>(null); //当前用户权限id
const allRequirements = ref<any>([]); // 我负责的所有需求
const searchFormData = ref({
  projectTitle: "",
  userName: "",
  time: [null, null],
});

const dialogInfoVisible = ref(false); //查看需求弹窗控件
const clearData = ref(false); //控制是否清空子组件数据
const isRequirementID = ref(); //当前操作任务ID

// 懒加载相关状态
const statusLoadingStates = ref<Record<number, boolean>>({}); // 每个状态的加载状态
const statusPageStates = ref<Record<number, number>>({}); // 每个状态的当前页码
const statusHasMoreStates = ref<Record<number, boolean>>({}); // 每个状态是否还有更多数据
const statusScrollStates = ref<Record<number, boolean>>({}); // 每个状态是否正在滚动加载

// 初始化状态数据
const initStatusData = () => {
  for (let i = 1; i <= 9; i++) {
    statusLoadingStates.value[i] = false;
    statusPageStates.value[i] = 1;
    statusHasMoreStates.value[i] = true;
    statusScrollStates.value[i] = false;
  }
};

// 获取指定状态的需求数据
const getRequirementsByStatus = async (status: number, isLoadMore = false) => {
  if (statusLoadingStates.value[status] || (!isLoadMore && !statusHasMoreStates.value[status])) {
    return;
  }

  statusLoadingStates.value[status] = true;
  statusScrollStates.value[status] = isLoadMore;

  try {
    const { data } = await postAllInitRequirement({
      projectTitle: searchFormData.value.projectTitle,
      beginTime: searchFormData.value.time === null ? null : searchFormData.value.time[0],
      endTime: searchFormData.value.time === null ? null : searchFormData.value.time[1],
      requirementStatus: status,
      page: statusPageStates.value[status],
      pageSize: 10,
      keyword: searchFormData.value.userName || ""
    });

    if (data.code === 200) {
      const responseData = data.data || {};
      const newRequirements = responseData.list || [];
      const total = responseData.total || 0;
      
      // 更新对应状态的数据
      const existingStatusIndex = allRequirements.value.findIndex((item: any) => item.status === status);
      
      if (existingStatusIndex >= 0) {
        // 如果已存在该状态，追加数据
        if (isLoadMore) {
          allRequirements.value[existingStatusIndex].requirements = [
            ...allRequirements.value[existingStatusIndex].requirements,
            ...newRequirements
          ];
        } else {
          allRequirements.value[existingStatusIndex].requirements = newRequirements;
          allRequirements.value[existingStatusIndex].total = total;
        }
      } else {
        // 如果不存在该状态，添加新状态
        allRequirements.value.push({
          status: status,
          total: total,
          requirements: newRequirements
        });
      }

      // 更新分页状态
      const currentStatusIndex = existingStatusIndex >= 0 ? existingStatusIndex : allRequirements.value.length - 1;
      const currentLoadedCount = allRequirements.value[currentStatusIndex]?.requirements.length || 0;
      
      if (newRequirements.length < 10 || currentLoadedCount >= total) {
        statusHasMoreStates.value[status] = false;
      } else {
        statusPageStates.value[status] += 1;
      }
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    console.error(`获取状态${status}需求失败:`, error);
    ElMessage.error(`获取状态${status}需求失败`);
  } finally {
    statusLoadingStates.value[status] = false;
    statusScrollStates.value[status] = false;
  }
};

// 获取所有状态的需求数据
const getAllRequirements = async () => {
  loading.value = true;
  userAuthId.value = localStorage.getItem("authorityId");
  
  // 重置所有状态数据
  initStatusData();
  allRequirements.value = [];

  // 并行获取所有状态的数据
  const promises = [];
  for (let i = 1; i <= 9; i++) {
    promises.push(getRequirementsByStatus(i, false));
  }

  try {
    await Promise.all(promises);
    
    // 按状态排序
    allRequirements.value.sort((a: any, b: any) => a.status - b.status);
    
    // 动态添加样式
    nextTick(() => {
      const cardLayoutBox = document.getElementById("cardLayoutBox");
      if (cardLayoutBox) {
        const length = allRequirements.value.length;
        if (length % 3 === 0) {
          cardLayoutBox.style.setProperty("justify-content", "space-between");
        } else {
          cardLayoutBox.style.setProperty("justify-content", "flex-start");
        }
      }
    });
  } catch (error) {
    console.error("获取需求数据失败:", error);
    ElMessage.error("获取需求数据失败");
  } finally {
    loading.value = false;
  }
};

// 懒加载处理函数
const handleScroll = (status: number) => {
  const cardListBox = document.getElementById(`card-list-box-${status}`);
  if (!cardListBox) return;

  const { scrollTop, scrollHeight, clientHeight } = cardListBox;
  const isNearBottom = scrollTop + clientHeight >= scrollHeight - 10;

  if (isNearBottom && statusHasMoreStates.value[status] && !statusLoadingStates.value[status]) {
    getRequirementsByStatus(status, true);
  }
};

// 查看需求
const handleRowClick = async (id: number) => {
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};

// TODO 关闭弹窗
const handleCloseDialog = () => {
  dialogInfoVisible.value = false;
  clearData.value = true;
};

onMounted(async () => {
  await useCommonStore.getAllRoleUsersList("");
  getAllRequirements();
});
</script>

<style lang="scss" scoped>
.content-container {
  display: flex;
  flex-direction: column;
  min-width: 1160px;
  height: 100%;
  overflow-x: auto;

  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    //height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-start;

    .search-wrap-item {
      margin-right: 10px;
      margin-bottom: 0;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  }

  // 需求列表区域
  .card-layout-box {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: row;
    //flex-wrap: wrap; 换行布局
    overflow-y: auto;
    border-radius: 6px;

    // 无数据时显示
    .card-not-requirement {
      color: #909399;
      margin: auto;
    }

    .card-box {
      //width: 32.6%;
      min-width: 380px;
      //height: 360px;
      height: 97%;
      border: 1px solid #d0d0d0;
      border-radius: 6px;
      margin: 0 0.3% 1% 0.3%;
      display: flex;
      flex-direction: column;
      background: #fff;

      // 列表标题
      .card-header-box {
        width: 100%;
        height: 40px;
        padding: 0 10px;
        line-height: 40px;
        font-size: 14px;
        font-family: Helvetica, Arial, sans-serif;
        //color: white;
        border-radius: 6px 6px 0 0;
        border-bottom: 1px solid #dbdfe0;
        color: #bac0cb;

        span {
          color: #fff;
          font-size: 14px;
        }
      }

      // 列表盒子
      .card-list-box {
        width: 100%;
        // height: calc(100% - 40px);
        display: flex;
        justify-content: flex-start;
        overflow-y: auto;

        .card-list {
          width: 100%;
          height: 100%;
          font-size: 14px;

          .card-list-item {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            border-bottom: 1px solid #ccc;
            width: 100%;
            min-height: 70px;
            //height: 70px;
            padding: 5px;

            // 操作
            .operate-box {
              width: 20px;
              height: 100%;
              display: flex;
              align-items: center;
            }

            .card-list-left {
              width: calc(100% - 20px);
              display: flex;
              flex-direction: column;
              flex-wrap: nowrap;
              justify-content: flex-start;
              position: relative;

              .icon-img {
                position: absolute;
                right: -25px;
                bottom: 0;
              }

              //需求类别
              .card-list-type {
                height: 20px;
                margin-bottom: 5px;

                img {
                  float: left;
                  padding-right: 5px;
                }

                span {
                  float: left;
                  display: inline-block;
                  height: 20px;
                  margin-right: 5px;
                }
              }

              // 需求标题
              .card-header-title-box {
                width: 100%;
                cursor: pointer;

                b {
                  font-size: 15px;
                }

                .el-text {
                  width: 100%;
                }

                .el-text:hover {
                  color: #409eff;
                }
              }

              .card-list-info-box {
                width: 100%;
                display: flex;
                flex-direction: column;

                // 附加信息样式
                .card-list {
                  width: 100%;
                  display: flex;
                  justify-content: space-between;
                  flex-direction: row;
                  white-space: nowrap;
                  padding: 0;
                  font-size: 0.7rem;

                  .card-list-small-item {
                    margin: 0 10px 0 0;
                    position: relative;
                  }

                  .begin-time {
                    width: 110px;
                    font-size: 12px;
                    position: relative;
                  }

                  .item-status {
                    width: 120px;
                  }

                  .boss-name {
                    width: 110px;
                  }

                  .test-list {
                    width: 180px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  }
                }

                .begin-time {
                  width: 100%;
                  padding: 2px 0;
                  display: flex;
                  flex-direction: row;
                  justify-content: flex-start;

                  .begin-time-first {
                    margin-right: 20px;
                  }
                }
              }

              .card-header-title-box:hover {
                color: #409eff;
              }
            }
          }
        }
      }
    }

    /* 当屏幕宽度超过 1620px 时，调整 .card-box 的宽度 */
    @media (min-width: 1921px) {
      .card-box {
        width: 24.2%;
        /* 新的宽度 */
      }
    }

    /* 当屏幕宽度超过 2680px 时，调整 .card-box 的宽度 */
    @media (min-width: 2681px) {
      .card-box {
        width: 19.32%;
        /* 新的宽度 */
      }
    }

    .card-list-item:hover {
      background-color: rgb(216.8, 235.6, 255);
    }
  }

  .red-text {
    color: red;
  }

  .red-bj {
    background-color: #fff1f0;
  }

  .card-finished {
    color: #999;
    text-decoration: line-through;
  }

  // 懒加载状态指示器样式
  .loading-indicator {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    color: #999;
    font-size: 12px;
    border-bottom: 1px solid #ccc;
    min-height: 50px;
    
    .loading-content {
      display: flex;
      align-items: center;
      justify-content: center;
      
      .el-icon {
        margin-right: 5px;
      }
    }
  }

  .no-more-data {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    color: #ccc;
    font-size: 12px;
    border-bottom: 1px solid #ccc;
    min-height: 50px;
    
    .no-more-content {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
